package com.sunxd.zjmh;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author sun.xd
 * @description: description
 * @date 2024/7/17 9:18
 */
public class Pdf2Image {

    //处理pdf文件
    public static void dealPdf(String inputPdfPath, String outputPngPath) {
        try {
            // 将PDF转换为PNG图像列表
            List<BufferedImage> images = convertPdfToPng(inputPdfPath);

            // 将PNG图像垂直排列合并为一个图像
            mergeVertically(images, outputPngPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //将每页pdf转成png并存储
    public static List<BufferedImage> convertPdfToPng(String pdfPath) throws IOException {
        // 加载PDF文档
        PDDocument document = PDDocument.load(new File(pdfPath));
        PDFRenderer renderer = new PDFRenderer(document);
        // 获取PDF页面数量
        int pageCount = document.getNumberOfPages();
        // 存储转换后的PNG图像
        List<BufferedImage> images = new ArrayList<>();
        // 遍历每一页并将其转换为PNG图像
        for (int i = 0; i < pageCount; i++) {
            BufferedImage image = renderer.renderImageWithDPI(i, 100);
//      ImageIO.write(image,"PNG",new File(i+".png"));
            images.add(image);
        }
        // 关闭PDF文档
        document.close();
        return images;
    }

    //合并png为一个整体
    public static void mergeVertically(List<BufferedImage> images, String outputPath) throws IOException {
        // 计算合并后的图像尺寸
        int totalHeight = 0;
        for (BufferedImage image : images) {
            totalHeight += image.getHeight();
        }

        // 创建一个新的空白图像，用于存放合并后的图像
        BufferedImage mergedImage = new BufferedImage(images.get(0).getWidth(), totalHeight, BufferedImage.TYPE_INT_RGB);

        // 将每一页的图像垂直堆叠在一起
        Graphics g = mergedImage.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, mergedImage.getWidth(), mergedImage.getHeight());
        int y = 0;
        for (BufferedImage image : images) {
            g.drawImage(image, 0, y, null);
            y += image.getHeight();
        }

        // 保存合并后的图像为PNG文件
        ImageIO.write(mergedImage, "PNG", new File(outputPath));
    }

    public static void main(String[] args) {
        String inputPdfPath = "C:\\Users\\sunxd\\Desktop\\save.pdf";
        String outputPngPath = "C:\\Users\\sunxd\\Desktop\\abc.png";
        dealPdf(inputPdfPath, outputPngPath);
    }
}
